package cn.ljn.basic.interceptor;


import cn.ljn.basic.annotation.PreAuthorize;
import cn.ljn.basic.jwt.JwtUtils;
import cn.ljn.basic.jwt.Payload;
import cn.ljn.basic.jwt.RsaUtils;
import cn.ljn.basic.jwt.UserInfo;
import cn.ljn.basic.util.ThreadLocalUtil;
import cn.ljn.system.mapper.PermissionMapper;
import cn.ljn.user.domain.Logininfo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.security.PublicKey;
import java.util.List;
import java.util.concurrent.TimeUnit;


/**
 * @Description: 登录拦截器
 * @Author: Mr.She
 * @Version: 1.0
 * @Date: 2022/6/13 16:54
 */
@Component // 需要加上此注解将当前登录拦截器交给spring管理
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private PermissionMapper permissionMapper;


    @Value("${jwt.pub}")
    private String jwtPub;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 3.如果能走到这里，说明token为空或者是Redis中用户信息为空，那么以未登录进行处理
        // 3.1.设置编码字符集
        response.setCharacterEncoding("UTF-8");
        // 3.2.设置响应参数类型为JSON
        response.setContentType("application/json;charset=UTF-8");

        // 1.获取前端请求头中的token信息
        String token = request.getHeader("token");

        // 2.判断前端请求是否携带token，如果携带那么进入判断
        if (!StringUtils.isEmpty(token)) {
            // 2.1.根据token获取到Redis中的用户信息
            PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource(jwtPub).getFile());
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, publicKey, UserInfo.class);
            // 2.2.如果用户信息不为空，那么刷新Redis中token有效期
            if (payload != null && payload.getUserInfo() != null ){
                UserInfo userInfo = payload.getUserInfo();
                ThreadLocalUtil.setUserInfo(userInfo);
                Logininfo logininfo = userInfo.getLogininfo();
                if (logininfo.getType() == 0){ // 如果是0的话代表管理员 只有后台管理员才进行权限判断
                    // 查询该登陆人的所有权限
                    List<String> snList = permissionMapper.findByLogininfoId(logininfo.getId());

                    HandlerMethod handlerMethod = (HandlerMethod) handler;
                    PreAuthorize preAuthorize = handlerMethod.getMethodAnnotation(PreAuthorize.class);
                    if (preAuthorize != null){
                        String sn = preAuthorize.sn();
                        if (!snList.contains(sn)){
                            // 3.3.获取到打印流,并设置响应数据
                            PrintWriter writer = response.getWriter();
                            writer.write("{\"success\":false,\"resultObj\":\"noPermission\"}");
                            // 3.4.刷新、关流
                            writer.flush();
                            writer.close();
                            return false;
                        }
                    }
                }
//                redisTemplate.expire(token, 3000000, TimeUnit.MINUTES);
                return true;
            }
        }
        // 3.3.获取到打印流,并设置响应数据
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"resultObj\":\"noLogin\"}");
        // 3.4.刷新、关流
        writer.flush();
        writer.close();
        return false;
    }
}